<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, message, Tag } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getMaterialStockDetailList, exportExpiredData } from '#/api/backend/materialStockDetail'
import { getWarehouseList } from '#/api/common'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import { AntPlusOutlined, AntDeleteOutlined } from '@vben/icons'
import { Input, Image } from 'ant-design-vue'
import StockRecordModalComponent from './modules/stockRecordModal.vue'

interface RowType {
  [key: string]: any
}

// 定义类型
interface MaterialStockDetailRow {
  id: number
  material_name: string
  sku_sn: string
  ware_house_id: number
  [key: string]: any
}

// const selectedRows = ref<MaterialStockDetailRow[]>([])
const formData = ref<any>({})
const keyword = ref({ warehouse_id: '' })
const showInStock = ref(false)
const selectedRows = ref<RowType[]>([])
const loading = ref(false)
const params = ref<any>({ quick_search: '' })

// 获取仓库选项
const fetchWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getWarehouseList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.ware_house_id,
    select: true,
  })
  return list.map((item: any) => ({ label: `${item.warehouse_code}/${item.warehouse_name}`, value: item.id }))
}

const fetchData = async () => {
  gridApi.reload()
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'material*material_name',
      label: '物料名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'materialSku*sku_sn',
      label: '物料编码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'in_stock',
      label: '库存',
      componentProps: {
        allowClear: true,
        options: [
          { label: '全部', value: 0 },
          { label: '仅看有库存', value: 1 },
        ],
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'ware_house_id',
      label: '仓库',
      operator: 'IN',
      componentProps: () => ({
        api: fetchWarehouseOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.warehouse_id = value
        }, 300),
        params: { keyword: keyword.value.warehouse_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.warehouse_id = ''
        },
      }),
    },
    // {
    //   component: 'Input',
    //   fieldName: 'color_name',
    //   label: '颜色',
    //   operator: 'LIKE',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    // {
    //   component: 'Input',
    //   fieldName: 'spec_name',
    //   label: '规格',
    //   operator: 'LIKE',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
   checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: { useKey: true },
  // cellConfig: { height: 60 },
  columns: [
    { type: 'checkbox', width: 50 },
    { field: 'id', width: 80, title: 'ID' },
    { field: 'warehouse_info', width: 150, title: '仓库', slots: { default: 'warehouseInfo' } },
    { field: 'material.material_name', width: 250, title: '物料名称' },
    { field: 'material.material_code', width: 140, title: '物料编码' },
    { field: 'color_name', width: 100, title: '颜色' },
    { field: 'spec_name', width: 100, title: '规格' },
    { field: 'stock', width: 120, title: '核料库存' },
    { field: 'material.check_price', width: 120, title: '核料单价' },
    { field: 'material.check_unit', width: 100, title: '核料单位' },
    { field: 'material.unit_rate', width: 100, title: '换算比例' },
    { field: 'cgstock', width: 120, title: '采购库存' },
    { field: 'material.price', width: 120, title: '采购单价' },
    { field: 'material.unit', width: 100, title: '采购单位' },
    {
      field: 'updated_at',
      width: 160,
      title: '更新时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    { field: 'operation', fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 120 },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = (await gridApi.formApi.getFiltersValues()) as Array<{ fieldName: string; operator: string; value: any }>
        if (showInStock.value) {
          search.push({ fieldName: 'in_stock', operator: '=', value: 1 })
        }
        const { list, total } = await getMaterialStockDetailList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          // order: sort.field && sort.order ? `${sort.field},${sort.order}` : `id,desc`,
        })
        return { items: list, total: total }
      },
    },
    sort: true,
  },
  sortConfig: { defaultSort: { field: 'id', order: 'desc' }, remote: true },
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'material_stock_detail_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})

const debouncedReload = useDebounceFn(gridApi.reload, 1000)

// 处理导出
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportExpiredData({ search })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 库存记录弹窗API
const [StockRecordModal, StockRecordModalApi] = useVbenModal({
  connectedComponent: StockRecordModalComponent,
})

// 处理库存明细
const handleShowStockRecord = (row: RowType) => {
  StockRecordModalApi.setData({
    materialSkuId: row.material_sku_id,
    warehouseId: row.ware_house_id,
  }).open()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleExport">导出</Button>
      </template>

      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="物料名称|物料编码|仓库名称" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #warehouseInfo="{ row }">
        <div>{{ row.warehouse?.warehouse_code }}/{{ row.warehouse?.warehouse_name }}</div>
      </template>

      <template #operation="{ row }">
        <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" size="small" @click.stop="handleShowStockRecord(row)">库存明细</Button>
      </template>
    </Grid>
    <StockRecordModal />
  </Page>
</template>
